package com.dwk.config;


import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * 配置类，发布确认高级
 */
@Configuration
public class ConfirmConfig {
    //交换机
    public static final String CONFIRM_EXCHANGE_NAME = "confirm.exchange";

    //队列
    public static final String CONFIRM_QUEUE_NAME = "confirm.queue";

    //备份交换机和备份队列、报警队列
    public static final String BACKUP_EXCHANGE_NAME = "backup.exchange";
    public static final String BACKUP_QUEUE_NAME = "backup.queue";
    public static final String WARNING_QUEUE_NAME = "warning.queue";

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //注入
    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback(new MyCallBack());
        rabbitTemplate.setReturnsCallback(new MyCallBack());
    }

    //声明交换机
    @Bean
    public DirectExchange confirmExchange(){
        return ExchangeBuilder
                .directExchange(CONFIRM_EXCHANGE_NAME)
                .durable(true)
                .alternate(BACKUP_EXCHANGE_NAME)
                .build();
    }

    //声明队列
    @Bean
    public Queue confirmQueue(){
       return QueueBuilder.durable(CONFIRM_QUEUE_NAME).build();
    }


    //绑定关系
    @Bean
    public Binding queueBinding(@Qualifier("confirmExchange") DirectExchange directExchange,
                                @Qualifier("confirmQueue") Queue queue){
        return BindingBuilder.bind(queue).to(directExchange).with("key1");
    }

    //备份交换机
    @Bean
    public FanoutExchange backupExchange(){
        return new FanoutExchange(BACKUP_EXCHANGE_NAME);
    }

    //备份队列
    @Bean
    public Queue backupQueue(){
        return QueueBuilder.durable(BACKUP_QUEUE_NAME).build();
    }
    //声明队列
    @Bean
    public Queue warningQueue(){
        return QueueBuilder.durable(WARNING_QUEUE_NAME).build();
    }

    //绑定
    @Bean
    public Binding backupQueueBindingbackupExchange(@Qualifier("backupExchange") FanoutExchange fanoutExchange,
                                @Qualifier("backupQueue") Queue queue){
        return BindingBuilder.bind(queue).to(fanoutExchange);
    }

    //绑定
    @Bean
    public Binding warningQueueBindingbackupExchange(@Qualifier("backupExchange") FanoutExchange fanoutExchange,
                                                    @Qualifier("warningQueue") Queue queue){
        return BindingBuilder.bind(queue).to(fanoutExchange);
    }

}
